package com.outfood.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outfood.common.eleme.ElemeOrder;
import com.outfood.common.eleme.Result;
import com.outfood.common.eleme.evaluate.ElemEvaluate;
import com.outfood.common.eleme.evaluate.OrderRateInfos;
import com.outfood.config.PythonServerConfig;
import com.outfood.domain.*;
import com.outfood.mapper.StoreMapper;
import com.outfood.service.IElemeEvaluateRecordService;
import com.outfood.service.IOrderService;
import com.outfood.service.IRuleService;
import com.outfood.service.IStoreService;
import com.outfood.utils.JavaScriptUtil;
import com.outfood.utils.RedisUtil;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.Search;
import com.rys.common.utils.StringUtils;
import groovyjarjarantlr.PythonCharFormatter;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.service.impl
 * @Date 2024-04-10 15:56
 * @Version 1.0
 */

@Log4j2
@Service
public class ElmeOperateServiceImpl {


    public static Map<String ,WebSocketClient> socketClients = new HashMap<>();

        @Data
       public static class Query{
             private String ksid;
             private String shopId;
             private Long orderId;
             private Long storeId;
        }

        @Resource
        IStoreService storeService;

        @Resource
        CreateElemeTokenService createElemeTokenService;

    private static RestTemplate createRestTemplateWithCustomInterceptor() {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 添加自定义拦截器
        restTemplate.setInterceptors(Collections.singletonList(new CustomInterceptor()));
        return restTemplate;
    }

    private static class CustomInterceptor implements ClientHttpRequestInterceptor {
        @Override
        public org.springframework.http.client.ClientHttpResponse intercept(
                org.springframework.http.HttpRequest request, byte[] body,
                org.springframework.http.client.ClientHttpRequestExecution execution) throws IOException {
            // 移除或修改请求头名称中的冒号
//            request.getHeaders()
//                    .entrySet()
//                    .stream()
//                    .filter(entry -> entry.getKey().startsWith(":"))
//                    .forEach(entry -> request.getHeaders().put(modifyHeaderName(entry.getKey()), entry.getValue()));

            // 执行请求
            return execution.execute(request, body);
        }

    }

        public List<Result> getOrderList(Query query){
            Store store = storeService.get(query.getStoreId());
            if(store.getPStoreId() != null && store.getOnlineStatus().equals("ONLINE")){
                log.info("如果父门存货，则子门店不用获取订单");
                return new ArrayList<>();
            }

            RestTemplate restTemplate = createRestTemplateWithCustomInterceptor();
            HttpHeaders headers = new HttpHeaders();

            String reqeustId = JavaScriptUtil.createRequestId();
            String params = "{\"service\":\"OrderWebService\",\"method\":\"queryInProcessOrders\",\"params\":{\"shopId\":"+query.getShopId()+",\"queryType\":\"COOKING\"},\"id\":\""+reqeustId+"\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+query.getKsid()+"\",\"shopId\":"+query.getShopId()+"},\"ncp\":\"2.0.0\"}";
            log.info("请求参数为{}",params);

            JSONObject jsonObject = JSON.parseObject(params);
            headers.add(":authority","app-api.shop.ele.me");
            headers.add(":method","POST");
            headers.add(":path","/fulfill/weborder/queryInProcessOrders/?method=OrderWebService.queryInProcessOrders");
            headers.add(":scheme","https");
            headers.add("Accept","application/json, text/plain, */*");
            headers.add("Accept-Encoding","gzip, deflate, br, zstd");
            headers.add("Accept-Language","zh-CN,zh;q=0.9");
            headers.add("Bx-Et",createElemeTokenService.getsign());
            headers.add("Content-Length",params.length()+"");
            headers.add("Content-Type","application/json;charset=UTF-8");
            headers.add("Origin","https://napos-order-pc.faas.ele.me");
            headers.add("Priority","u=1, i");
            headers.add("Referer","https://napos-order-pc.faas.ele.me/");
            headers.add("Sec-Ch-Ua","\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            headers.add("Sec-Ch-Ua-Mobile","?0");
            headers.add("Sec-Ch-Ua-Platform","\"Windows\"");
            headers.add("Sec-Fetch-Dest","empty");
            headers.add("Sec-Fetch-Mode","cors");
            headers.add("Sec-Fetch-Site","same-site");
            headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
            headers.add("X-Eleme-Requestid",reqeustId);
            headers.add("X-Shard","shopid="+query.shopId);
            log.info("getorderList的请求头为{}",headers);
            HttpEntity request = new HttpEntity<>(jsonObject,headers);
            log.info("获取订单请求参数为{}",jsonObject);
            String url = "https://app-api.shop.ele.me/fulfill/weborder/queryInProcessOrders/?method=OrderWebService.queryInProcessOrders";
            ResponseEntity<String> jsonObjectResponseEntity = null;
            try {
                jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
            } catch (Exception e) {
                log.error("获取订单失败",e);
                if("401 Unauthorized".equals(e.getMessage())){
                    log.info("登录失效");
                    log.warn("门店{}登录失效",query.getStoreId());
                    if(store.getPStoreId() != null && store.getOnlineStatus().equals("ONLINE")){
                        log.info("父门店还存活，不用修改状态");
                    }else{
                        log.info("不存在父门店，直接设置离线");
                        store.setOnlineStatus("OFF");
                        store.setOffReason("401 Unauthorized");
                        storeService.update(store.getId(),store,"task");
                        meiTuanOperateService.downNotice(query.getStoreId());
                    }

                }
            }
            log.info(jsonObjectResponseEntity.getBody());
            ElemeOrder elemeOrder = JSON.parseObject(jsonObjectResponseEntity.getBody(), ElemeOrder.class);
            List<Result> result = elemeOrder.getResult();

            return CollectionUtils.isEmpty(result)?new ArrayList<>():result;
        }

    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;


    @Resource
    RestTemplate restTemplate;

    //账号密码登录
    public com.outfood.common.common.Result loginByUsernamepassword(String username, String password){
        String result = restTemplate.getForObject("/usernamepasswordeleme?huburl=http://172.16.0.252:4444/wd/hub&username=" + username + "&password=" + password, String.class);
        log.info(result);

        com.outfood.common.common.Result optionResult = JSON.parseObject(result, com.outfood.common.common.Result.class);
//        SeleniumService seleniumService = new SeleniumServiceImpl();
//        com.outfood.common.common.Result optionResult = seleniumService.loginByPassword(username, password);
        if(!optionResult.isSuccess()){
            throw new BusinessException(optionResult.getMessage());
        }
        return optionResult;

    }


    //账号密码登录
    public com.outfood.common.common.Result loginByCode(String code){
        String result = restTemplate.getForObject("/loginByCodeEleme?code="+code, String.class);
        log.info(result);

        com.outfood.common.common.Result optionResult = JSON.parseObject(result, com.outfood.common.common.Result.class);
//        SeleniumService seleniumService = new SeleniumServiceImpl();
//        com.outfood.common.common.Result optionResult = seleniumService.loginByPassword(username, password);
        if(!optionResult.isSuccess()){
            throw new BusinessException(optionResult.getMessage());
        }
        return optionResult;

    }




    @Resource
    private IOrderService orderService;

//    public static void main(String[] args) {
//        String originalString = "Example";
//        String modifiedString = originalString.substring(1);
//        System.out.println(modifiedString);
//    }

    public void loadFinlish(WebDriver webDriver){
        new WebDriverWait(webDriver, 3).until((WebDriver driver) -> {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            Boolean result = (Boolean) js.executeScript("return document.readyState === 'complete'");
            log.info("页面是否已经加载完成"+result);
            return result;
        });
    }

    

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","C:\\drive\\chromedriver.exe");
        SeleniumServiceImpl seleniumService = new SeleniumServiceImpl();
        WebDriver webDriver = seleniumService.getWebDriver();
        webDriver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
        webDriver.get("https://melody.shop.ele.me/login");
        String elemstorage = readFile("E:\\outfoodcat\\outfoodcat-master\\outfood-admin\\src\\main\\resources\\storage.txt");
        Map<String,Object> map = JSON.parseObject(elemstorage, Map.class);
        map.remove("APLUS_LS_KEY");
        JavascriptExecutor js = (JavascriptExecutor) webDriver;
        for (Object o : map.keySet()) {
            try {
                System.out.println(map.get(o));
                String script = "window.localStorage.setItem('"+o+"','"+map.get(o).toString().replaceAll("'","\"")+"')";
                System.out.println(script);
                js.executeScript(script);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        String regionId = "90940970";
        webDriver.get("https://melody.shop.ele.me/app/shop/"+regionId+"/order__processing#app.shop.order.processing");
        webDriver.switchTo().frame("app_shop_order_processing");
    }

    public static String readFile(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n"); // 保留换行符，如果需要的话
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return contentBuilder.toString();
    }

    @Resource
    RedisUtil redisUtil;
    @SneakyThrows
    public OutResult excuteOutFood(Query query){
        WebDriver webDriver = null;
        String targetUrl = "";
        Store store = null;
        try {
            Order order = orderService.get(query.getOrderId());
            SeleniumServiceImpl seleniumService = new SeleniumServiceImpl();
            store = storeService.get(query.getStoreId());
            webDriver = seleniumService.getWebDriver();
            webDriver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
            webDriver.get("https://melody.shop.ele.me/login");
            String elemstorage = redisUtil.getStorage(store.getId());
            Map map = JSON.parseObject(elemstorage, Map.class);
            map.remove("APLUS_LS_KEY");
            JavascriptExecutor js = (JavascriptExecutor) webDriver;
            for (Object o : map.keySet()) {
                try {
                    String script = "window.localStorage.setItem('"+o+"','"+map.get(o)+"')";
                    js.executeScript(script);
                } catch (Exception e) {
                    log.error("",e);
                }

            }
            targetUrl = "https://melody.shop.ele.me/app/shop/"+store.getRegionId()+"/order__processing#app.shop.order.processing";
            webDriver.get(targetUrl);
            webDriver.switchTo().frame("app_shop_order_processing");

            loadFinlish(webDriver);
            js.executeScript("document.querySelector(\"#rc-tabs-0-tab-all > span > span\").click()");
            Thread.sleep(1000L);
            try {  //进行判断
                if(StringUtils.isBlank(order.getIncome())){
                    String income = (String) js.executeScript("return document.querySelector(\"#\\\\38 "+order.getOutTradeNo().substring(1)+" > div.order-card-item__2m71tc1Es8xRDBwVQ0-tog > div.order-card-itemRight__gZnAP-2wmW-uidO2qhMs0 > div.expectedIncome__1_9MNgOynAKQJCiZmGQSEk > div:nth-child(2) > span\").innerText");
                    System.out.println("获取到的income为"+income);
                    income = income.replace("¥","");
                    order.setIncome(income);
                    orderService.update(order.getId(),order,"task");
                    Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, store.getId())).get(0);
                    Integer time = ruleService.getTime(rule.getId(), income);
                    log.info("获取到的理论出餐时间为"+time);
                    log.info("获取到的最低出餐时间为"+rule.getTime());
                    if(!time.equals(rule.getTime()) ){
                        log.info("time={},rule.gettime={}",time,rule.getTime());
                        order.setTheoryOutTime(new Date(order.getTheoryOutTime().getTime()+((time-rule.getTime())*1000*60)));
                        orderService.update(order.getId(),order,"task");
                        return null;
                    }
                }
            } catch (Exception e) {
            }
            String a = "document.querySelector(\"#\\\\38 "+order.getOutTradeNo().substring(1)+" > div.meal-complete-content__629EC9g1eSK9XyD7yb-Ok.order-content-base__1KDsrTr1JhR-nZefiIqb84 > button\").click()";
            log.info(a);
            js.executeScript(a);
            Thread.sleep(1000L);

            try {
                //点击真实上报
                js.executeScript("document.querySelector(\"body > div > div > div > div > div.ant-popover-inner > div > div.ant-popover-buttons > button.ant-btn.ant-btn-primary.ant-btn-sm\").click()");
                log.error("成功点击了真实上报");
            } catch (Exception e) {
                log.error("点击真实上报错误");
            }
            Thread.sleep(1000L);
            order.setOutStatus("OUTED");
            order.setOutFoodTime(new Date());
            orderService.update(order.getId(),order,"task");


        } catch (Exception e) {
            throw e;
        }finally {
            webDriver.quit();
        }
        OutResult result = new OutResult();

        //document.querySelector("#\\38 048650075509706147 > div.meal-complete-content__629EC9g1eSK9XyD7yb-Ok.order-content-base__1KDsrTr1JhR-nZefiIqb84 > button")
        //document.querySelector("#\\38 8048650075509706147 > div.meal-complete-content__629EC9g1eSK9XyD7yb-Ok.order-content-base__1KDsrTr1JhR-nZefiIqb84 > button").click()
        //document.querySelector("#\\38 008330150610447827 > div.meal-complete-content__629EC9g1eSK9XyD7yb-Ok.order-content-base__1KDsrTr1JhR-nZefiIqb84 > button")
//
//
//        String params = "{\"service\":\"ShipmentService\",\"method\":\"mealComplete\",\"params\":{\"orderId\":\""+order.getOutTradeNo()+"\",\"shopId\":"+order.getPoiId()+"},\"id\":\""+reqeustId+"\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+query.getKsid()+"\",\"shopId\":"+order.getPoiId()+"},\"ncp\":\"2.0.0\"}";
//
//        headers.add(":authority","app-api.shop.ele.me");
//        headers.add(":method","POST");
//        headers.add(":path","/fulfill/weborder/mealComplete/?method=ShipmentService.mealComplete");
//        headers.add(":scheme","https");
//        headers.add("Accept","application/json, text/plain, */*");
//        headers.add("Accept-Encoding","gzip, deflate, br, zstd");
//        headers.add("Accept-Language","zh-CN,zh;q=0.9");
//        headers.add("Bx-Et",createElemeTokenService.getsign());
//        headers.add("Content-Length",params.length()+"");
//        headers.add("Content-Type","application/json;charset=UTF-8");
//        headers.add("Origin","https://napos-order-pc.faas.ele.me");
//        headers.add("Priority","u=1, i");
//        headers.add("Referer","https://napos-order-pc.faas.ele.me/");
//        headers.add("Sec-Ch-Ua","\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
//        headers.add("Sec-Ch-Ua-Mobile","?0");
//        headers.add("Sec-Ch-Ua-Platform","\"Windows\"");
//        headers.add("Sec-Fetch-Dest","empty");
//        headers.add("Sec-Fetch-Mode","cors");
//        headers.add("Sec-Fetch-Site","same-site");
//        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
//        headers.add("X-Eleme-Requestid",reqeustId);
//        headers.add("X-Shard","shopid="+order.getPoiId());
//        log.info("excuteOutfood的请求头为{}",headers);
//        JSONObject jsonObject = JSON.parseObject(params);
//        HttpEntity request = new HttpEntity<>(jsonObject,headers);
//        String url = "https://app-api.shop.ele.me/fulfill/weborder/mealComplete/?method=ShipmentService.mealComplete";
//        ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
//        log.info("饿了么出餐结果为",jsonObjectResponseEntity.getBody());
//        if(jsonObjectResponseEntity.getBody().contains("sessionStorage")){
//            OutResult outResult = new OutResult();
//            outResult.setError("000000");
//            return outResult;
//        }
//        OutResult result = JSON.parseObject(jsonObjectResponseEntity.getBody(), OutResult.class);
//        trace(query);
        return result;

    }


    //查询所有带出餐的订单
    public void trace(Query query){
        try {
            log.info("开始trace....");
            Order order = orderService.get(query.getOrderId());
            RestTemplate restTemplate = createRestTemplateWithCustomInterceptor();
            String reqeustId = JavaScriptUtil.createRequestId();
            HttpHeaders headers = new HttpHeaders();
            String params = "{\"service\":\"TraceService\",\"method\":\"trace\",\"params\":{\"orderIds\":[\""+order.getOutTradeNo()+"\"],\"action\":\"PREPARE_MEAL\",\"extra\":{\"actionType\":\"CLICK\"}},\"id\":\""+reqeustId+"\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+query.getKsid()+"\",\"shopId\":"+query.getShopId()+"},\"ncp\":\"2.0.0\"}";

            headers.add(":authority","app-api.shop.ele.me");
            headers.add(":method","POST");
            headers.add(":path","/fulfill/weborder/trace/?method=TraceService.trace");
            headers.add(":scheme","https");
            headers.add("Accept","application/json, text/plain, */*");
            headers.add("Accept-Encoding","gzip, deflate, br, zstd");
            headers.add("Accept-Language","zh-CN,zh;q=0.9");
            headers.add("Bx-Et",createElemeTokenService.getsign());
            headers.add("Content-Length",params.length()+"");
            headers.add("Content-Type","application/json;charset=UTF-8");
            headers.add("Origin","https://napos-order-pc.faas.ele.me");
            headers.add("Priority","u=1, i");
            headers.add("Referer","https://napos-order-pc.faas.ele.me/");
            headers.add("Sec-Ch-Ua","\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            headers.add("Sec-Ch-Ua-Mobile","?0");
            headers.add("Sec-Ch-Ua-Platform","\"Windows\"");
            headers.add("Sec-Fetch-Dest","empty");
            headers.add("Sec-Fetch-Mode","cors");
            headers.add("Sec-Fetch-Site","same-site");
            headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
            headers.add("X-Eleme-Requestid",reqeustId);
            headers.add("X-Shard","shopid="+order.getPoiId());
            log.info("tarce的请求头为{}",headers);

            log.info("trace参数为....{}",params);
            JSONObject jsonObject = JSON.parseObject(params);
            HttpEntity request = new HttpEntity<>(jsonObject,headers);
            String url = "https://app-api.shop.ele.me/fulfill/weborder/trace/?method=TraceService.trace";
            ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
            log.info("饿了么出餐结果为",jsonObjectResponseEntity.getBody());
            log.info("trace结束....结果为{}",jsonObjectResponseEntity.getBody());
        } catch (RestClientException e) {
            log.error(e.getMessage(),e);
        }


    }


    @Resource
    IRuleService ruleService;

    private void getOrdersByStore(Store store) {
        try {
            Thread.sleep(new Random().nextInt(1000));
            if("FALSE".equals(store.getAutoOut())){
                log.warn("{}没有开启自动出餐", store.getStoreName());
                return;
            }
            ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
            query.setShopId(store.getRegionId());
            query.setKsid(store.getCookie());
            query.setStoreId(store.getId());
            List<Result> orderList = this.getOrderList(query);
            if(CollectionUtils.isEmpty(orderList)){
                return;
            }

            orderList.forEach(orderItem ->{
                List<Store> ss = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, orderItem.getShopId()));
                if(CollectionUtils.isEmpty(ss)){
                    return;
                }
                if("FALSE".equals(ss.get(0).getAutoOut())){
                    log.warn("{}子门店没有开启自动出餐", store.getStoreName());
                    return;
                }
                Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, ss.get(0).getId())).get(0);
                Order order = new Order();
                order.setOrderTime(orderItem.getActiveTime());
                order.setTheoryOutTime(new Date(order.getOrderTime().getTime()+1000*60*rule.getTime()));
                //order.setBuyerName(orderItem.get);
                String foodName = orderItem.getFoodInfo().getGroups().get(0).getItems().stream().map(item -> item.getName()).collect(Collectors.joining(","));
                order.setFoodName(foodName);

//                    order.setIncome(orderItem.getDetail().getChargeInfo().getFixedSettlementInfo().getSettleAmount()+"");
//                    order.setPoiId(orderItem.getCommonInfoObj().getWmPoiId()+"");
//                    order.setOrderNo(orderItem.getCommonInfoObj().getWm_poi_order_dayseq()+"");
//                    order.setBuyerName(orderItem.getDetail().getUserInfo().getRecipientName());
                order.setOutStatus("READY");
                order.setStoreId(store.getId());
                order.setOrderNo(orderItem.getHeader()
                        .getDaySn());
                order.setOrderSource("ELEME");
                order.setOutTradeNo(orderItem.getId());
                order.setPoiId(orderItem.getShopId()+"");
//                    order.setRider(orderItem.getDetail().getLogisticsInfo().getTitle());
//                    order.setOutTradeNo(orderItem.getCommonInfoObj().getWm_order_id_view()+"");
//                    order.setInfo(JSON.toJSONString(orderItem));
                List<Order> result = orderService.getList(new Search().add("outTradeNo", SearchTypeEnum.EqualTo, orderItem.getId()));
                if(CollectionUtils.isEmpty(result)){
                    orderService.add(order,"task");
                }

            });
        } catch (Exception e) {
            log.error("获取订单失败",e);
        }
    }

    //查询所有带出餐的订单
    public void getAccessToken(Query query) {
        Store store = new Store();
        try {
            log.info("开始获取token....");
            store = storeService.get(query.getStoreId());
            RestTemplate restTemplate = createRestTemplateWithCustomInterceptor();
            String reqeustId = JavaScriptUtil.createRequestId();
            HttpHeaders headers = new HttpHeaders();
            String params = "{\"service\":\"AuthCenterService\",\"method\":\"getToken\",\"params\":{\"shopId\":\"" + store.getRegionId() + "\"},\"id\":\"" + reqeustId + "\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\"" + store.getCookie() + "\",\"shopId\":" + store.getRegionId() + "},\"ncp\":\"2.0.0\"}";
            headers.add(":authority", "app-api.shop.ele.me");
            headers.add(":method", "POST");
            headers.add(":path", "/fulfill/device/controller/getAccsToken/?method=AuthCenterService.getToken");
            headers.add(":scheme", "https");
            headers.add("Accept", "application/json, text/plain, */*");
            headers.add("Accept-Encoding", "gzip, deflate, br, zstd");
            headers.add("Accept-Language", "zh-CN,zh;q=0.9");
            headers.add("Bx-Et", createElemeTokenService.getsign());
            headers.add("Content-Length", params.length() + "");
            headers.add("Content-Type", "application/json;charset=UTF-8");
            headers.add("Origin", "https://napos-order-pc.faas.ele.me");
            headers.add("Priority", "u=1, i");
            headers.add("Referer", "https://napos-order-pc.faas.ele.me/");
            headers.add("Sec-Ch-Ua", "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            headers.add("Sec-Ch-Ua-Mobile", "?0");
            headers.add("Sec-Ch-Ua-Platform", "\"Windows\"");
            headers.add("Sec-Fetch-Dest", "empty");
            headers.add("Sec-Fetch-Mode", "cors");
            headers.add("Sec-Fetch-Site", "same-site");
            headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
            headers.add("X-Eleme-Requestid", reqeustId);
            headers.add("X-Shard", "shopid=" + store.getRegionId());

            log.info("auth参数为....{}", params);
            JSONObject jsonObject = JSON.parseObject(params);
            HttpEntity request = new HttpEntity<>(jsonObject, headers);
            String url = "https://app-api.shop.ele.me/fulfill/device/controller/getAccsToken/?method=AuthCenterService.getToken";
            ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
            log.info("饿了么认证结果为", jsonObjectResponseEntity.getBody());
            log.info("认证结束....结果为{}", jsonObjectResponseEntity.getBody());
            JSONObject result = JSON.parseObject(jsonObjectResponseEntity.getBody());
            String string = result.getJSONObject("result").getString("token");
            log.info("token为{}", string);
            Store finalStore = store;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    connect(string, finalStore.getStoreName(), finalStore.getId());
                }
            }).start();

        } catch (Exception e) {
            if("401 Unauthorized".equals(e.getMessage())){
                log.info("登录失效");
                log.warn("门店{}登录失效",query.getStoreId());
                if(store.getPStoreId() != null && store.getOnlineStatus().equals("ONLINE")){
                    log.info("父门店还存活，不用修改状态");
                }else{
                    log.info("不存在父门店，直接设置离线");
                    store.setOnlineStatus("OFF");
                    store.setOffReason("401 Unauthorized");
                    storeService.update(store.getId(),store,"task");
                    meiTuanOperateService.downNotice(query.getStoreId());
                }

            }
            log.error(e.getMessage(), e);
        }
    }

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    ScheduledExecutorService scheduledExecutorService;

    /**
     * Copyright 2024 bejson.com


    /**
     * Auto-generated: 2024-05-30 10:27:34
     *
     * @author bejson.com (i@bejson.com)
     * @website http://www.bejson.com/java2pojo/
     */
    @Data
    public static class Content {

        private int daySn;
        private List<String> orderIds;
        private long shopId;
        private long sendTime;

    }

    @Data
    public static class SocketContnet {

        private String oldTopic;
        private String msgId;
        private String topic;
        private Content content;
        private boolean required;


    }


    public static List<Content> createContent(String body) {
//        String a = "{\"message\":\"[{\\\"content\\\":{\\\"daySn\\\":4,\\\"orderIds\\\":[\\\"8057540075072723285\\\"],\\\"sendTime\\\":1717035621000,\\\"shopId\\\":1197865222},\\\"msgId\\\":\\\"6110000069317983780\\\",\\\"oldTopic\\\":\\\"order.order.unprocess\\\",\\\"required\\\":true,\\\"topic\\\":\\\"TRADE.ESCROW.ORDER.WAIT.ACCEPT\\\"}]\"}";
        JSONObject jsonObject = JSON.parseObject(body);
        String message = jsonObject.getString("message");
        List<SocketContnet> socketContnets = JSON.parseArray(message, SocketContnet.class);
        List<Content> content = socketContnets.stream().filter(socketContnet -> {
            if ("TRADE.ESCROW.ORDER.WAIT.ACCEPT".equals(socketContnet.getTopic()) || "FULFILL.DELIVERY.STATUS_CHANGED".equals(socketContnet.getTopic())) {
                return true;
            } else {
                return false;
            }
        }).map(socketContnet -> {
            return socketContnet.getContent();
        }).collect(Collectors.toList());
        return content;
    }

    public  void connect(String token,String storeName,Long storeId ) {
        try {
            URI uri = new URI("wss://ws-msgacs.m.taobao.com/accs/auth?token="+token);
            WebSocketClient webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    System.out.println(storeName+"新连接已打开");
                }

                @Override
                public void onMessage(String message) {
                    System.out.println(storeName+"接收到了消息: " + message);
                    try {
                        try {
                            System.out.println(message);
                            JSONObject jsonObject = JSON.parseObject(message);
                            if("COMMON".equals(jsonObject.getString("compressType"))){
                                String data = jsonObject.getString("data");
                                String content = JavaScriptUtil.textDecode(data);
                               System.out.println(content);
                               log.error(content);
                                List<Content> resultList = createContent(content);
                                System.out.println(resultList);
                                resultList.forEach(ct -> {
                                    saveOrder(ct);
                                });


                            }


                        } catch (Exception e) {
                            System.out.println("解析失败");
                        }
                    } catch (Exception e) {
                        log.error("socket获取订单失败",e);
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    System.out.println(storeName+"连接已关闭");
//                    ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
//                    Store store = storeService.get(storeId);
//                    query.setShopId(store.getRegionId());
//                    query.setKsid(store.getCookie());
//                    query.setStoreId(store.getId());
//                    getAccessToken(query);
                }

                @Override
                public void onError(Exception ex) {
                    ex.printStackTrace();
                }
            };

            webSocketClient.connect();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    while(true){
                        System.out.println(storeName+"发送心跳。。。");
                        webSocketClient.send("{\"type\":\"ACK\",\"protocol\":\"HEARTBEAT_ACCS_H5\",\"data\":\"\"}");
                        try {
                            Thread.sleep(30000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }).start();

            try {
                String key = storeId+"";
                WebSocketClient cli = socketClients.get(key);
                if(cli != null){
                    System.out.println("移除原有的socket.......");
                    try {
                        cli.close();
                    } catch (Exception e) {

                    }
                    socketClients.put(key,webSocketClient);
                }else{
                    socketClients.put(key,webSocketClient);
                }
            } catch (Exception e) {

            }

//            scheduledExecutorService.schedule(new Runnable() {
//                @Override
//                public void run() {
//                    System.out.println(storeName+"连接到期关闭");
//                    webSocketClient.close();
//                }
//            },1,TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Resource
    PythonServerConfig pythonServerConfig;

    private synchronized  void saveOrder(Content orderItem) {
        String outstatus = (String) redisTemplate.opsForValue().get("outstatus:" + orderItem.getOrderIds().get(0));
        if("OUTED".equals(outstatus)){ //这一笔订单已经成功了 不用在处理了
            log.info(orderItem.getOrderIds().get(0)+"已出，无需处理");
            return;
        }else{
            log.info(orderItem.getOrderIds().get(0)+"没有出餐或者出餐异常开始处理");
        }
        List<Store> ss = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, orderItem.getShopId()));
        if(CollectionUtils.isEmpty(ss)){
            return;
        }
        if("FALSE".equals(ss.get(0).getAutoOut())){
            log.warn("{}子门店没有开启自动出餐");
            return;
        }
        Store store = ss.get(0);
        if("2".equals(store.getStoreStatus())){
            return;
        }
        if(!"ONLINE".equals(store.getOnlineStatus())){
            log.warn("该门店掉线不出餐");
            return;
        }
        Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, ss.get(0).getId())).get(0);
        Order order = new Order();
        order.setOrderTime(new Date(orderItem.getSendTime()));
        order.setTheoryOutTime(new Date(order.getOrderTime().getTime()+1000*60*rule.getTime()-16*1000));
        //order.setBuyerName(orderItem.get);
        String foodName = "";

//                    order.setIncome(orderItem.getDetail().getChargeInfo().getFixedSettlementInfo().getSettleAmount()+"");
//                    order.setPoiId(orderItem.getCommonInfoObj().getWmPoiId()+"");
//                    order.setOrderNo(orderItem.getCommonInfoObj().getWm_poi_order_dayseq()+"");
//                    order.setBuyerName(orderItem.getDetail().getUserInfo().getRecipientName());
        order.setOutStatus("READY");
        order.setStoreId(store.getId());
        order.setOrderNo(orderItem.getDaySn()+"");
        order.setOrderSource("ELEME");
        order.setServerId(pythonServerConfig.getServerId());
        order.setOutTradeNo(orderItem.getOrderIds().get(0));
        order.setPoiId(orderItem.getShopId()+"");
//                    order.setRider(orderItem.getDetail().getLogisticsInfo().getTitle());
//                    order.setOutTradeNo(orderItem.getCommonInfoObj().getWm_order_id_view()+"");
//                    order.setInfo(JSON.toJSONString(orderItem));
        List<Order> result = orderService.getList(new Search().add("outTradeNo", SearchTypeEnum.EqualTo, orderItem.getOrderIds().get(0)));
        if(CollectionUtils.isEmpty(result)){
            orderService.add(order,"task");
        }else{
            Order odr = result.get(0);
            if("EXCEPT".equals(odr.getOutStatus())){
                odr.setOutStatus("READY");
                odr.setTheoryOutTime(new Date());
                orderService.update(odr.getId(),odr,"reupdate");
            }
        }
    }
    /**
     * Auto-generated: 2024-04-10 18:40:1
     *
     * @author bejson.com (i@bejson.com)
     * @website http://www.bejson.com/java2pojo/
     */
    @Data
    public static class OutResult {

        private String income;
        private String ncp;
        private String id;
        private String result;
        private String error;


    }


    @Resource
    IElemeEvaluateRecordService elemeEvaluateRecordService;


    public void getEvaluateList(Long storeId){
        Store store = storeService.get(storeId);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Bx-Et",createElemeTokenService.getsign());
        MeiTuanOperateServiceImpl.Range range = getRange();
        String params = "{\"service\":\"ShopRatingService\",\"method\":\"getRateResult\",\"params\":{\"rateQuery\":{\"shopIds\":["+store.getRegionId()+"],\"startTime\":\""+range.getStartTime()+"\",\"endTime\":\""+range.getEndTime()+"\",\"isReplied\":false,\"rateType\":\"ALL\",\"rateSourceType\":\"ELEME\",\"rateContentType\":\"ALL\",\"currentPage\":1,\"offset\":0,\"limit\":10}},\"id\":\"60236B7F18854A30B26BFC74715D4861|1715154506922\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+store.getCookie()+"\",\"shopId\":"+store.getRegionId()+"},\"ncp\":\"2.0.0\"}";
        JSONObject jsonObject = JSON.parseObject(params);
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        HttpEntity request = new HttpEntity<>(jsonObject,headers);
        String url = "https://app-api.shop.ele.me/ugc/invoke/?method=ShopRatingService.getRateResult";
        ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request, String.class);
        ElemEvaluate elemEvaluate = JSON.parseObject(jsonObjectResponseEntity.getBody(), ElemEvaluate.class);
        elemEvaluate.getResult().getRateInfos().forEach(item -> {
            try {
                if(item.getOrderRateInfos().get(0).getRatingAt().getTime() + (1000*60*60*24*10) < new Date().getTime()){ //只对10天之前的评论进行保存
                    return;
                }
                try {
                    List<ElemeEvaluateRecord> list = elemeEvaluateRecordService.getList(new Search().add("evaluateId", SearchTypeEnum.EqualTo, item.getOrderRateInfos().get(0).getRateId()));
                    if(CollectionUtils.isNotEmpty(list)){
                        return;
                    }
                    log.info(JSON.toJSONString(item));
                    ElemeEvaluateRecord evaluateRecord = new ElemeEvaluateRecord();
                    evaluateRecord.setUserName(item.getUsername());
                    evaluateRecord.setCityName("");
                    evaluateRecord.setEcomment("");
                    evaluateRecord.setFoodName("");
                    OrderRateInfos orderRateInfos = item.getOrderRateInfos().get(0);

                    evaluateRecord.setPackagingScore(orderRateInfos.getPackageRating()+"");
                    evaluateRecord.setTasteScore(item.getDishScore()+"");
                    evaluateRecord.setUserPicUrl("");
                    evaluateRecord.setWmPoiId("");
                    evaluateRecord.setEvaluateTime(orderRateInfos.getRatingAt());
                    evaluateRecord.setDeliveryCommentScore(orderRateInfos.getServiceRating()+"");
                    evaluateRecord.setOrderCommentScore(orderRateInfos.getQualityRating()+"");
                    evaluateRecord.setEvaluateId(orderRateInfos.getRateId());
                    evaluateRecord.setReplayResult("NOT");
                    evaluateRecord.setOrderCommentScore(orderRateInfos.getQualityRating()+"");
                    evaluateRecord.setEvaluatePicUrl("");
                    evaluateRecord.setComment(orderRateInfos.getRatingContent());
                    evaluateRecord.setAuditStatus("");
                    evaluateRecord.setCommentType("");
                    evaluateRecord.setRemark(JSON.toJSONString(item));
                    evaluateRecord.setStoreId(store.getId());
                    elemeEvaluateRecordService.add(evaluateRecord,"task");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                log.error("饿了么保存评价失败",e);
            }
        });

    }


    public void replay(Long evaluateId,String comment){
        ElemeEvaluateRecord elemeEvaluateRecord = elemeEvaluateRecordService.get(evaluateId);
        Store store = storeService.get(elemeEvaluateRecord.getStoreId());
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Bx-Et",createElemeTokenService.getsign());
        MeiTuanOperateServiceImpl.Range range = getRange();
        String params = "{\"service\":\"ShopRatingService\",\"method\":\"replyRating\",\"params\":{\"shopId\":"+store.getRegionId()+",\"reply\":{\"ratingComeFrom\":\"ELEME\",\"ratingId\":\""+elemeEvaluateRecord.getEvaluateId()+"\",\"ratingType\":\"ORDER\",\"content\":\""+comment+"\",\"templateId\":\"\"}},\"id\":\"44A655B30A3F436B92B042614DF8D903|1713172837446\",\"metas\":{\"appVersion\":\"1.0.0\",\"appName\":\"melody\",\"ksid\":\""+store.getCookie()+"\",\"shopId\":"+store.getRegionId()+"},\"ncp\":\"2.0.0\"}";
        JSONObject jsonObject = JSON.parseObject(params);
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        HttpEntity request = new HttpEntity<>(jsonObject,headers);
        String url = "https://app-api.shop.ele.me/ugc/invoke/?method=ShopRatingService.getRateResult";
        ResponseEntity<String> jsonObjectResponseEntity = null;
        try {
            jsonObjectResponseEntity  = restTemplate.postForEntity(url, request, String.class);
            log.info("饿了么评价结果返回{}",jsonObjectResponseEntity.getBody());
            if(!jsonObjectResponseEntity.getBody().contains("sessionStorage")){
                elemeEvaluateRecord.setReplayResult("HAS");
                elemeEvaluateRecord.setReplayMsg(comment);
                elemeEvaluateRecord.setEcomment(jsonObjectResponseEntity.getBody());
                elemeEvaluateRecordService.update(elemeEvaluateRecord.getId(),elemeEvaluateRecord,"task");
            }
        } catch (RestClientException e) {
            elemeEvaluateRecord.setReplayResult("EXCEPT");
            elemeEvaluateRecord.setReplayMsg(e.getMessage());
            elemeEvaluateRecord.setEcomment(jsonObjectResponseEntity.getBody());
            elemeEvaluateRecordService.update(elemeEvaluateRecord.getId(),elemeEvaluateRecord,"task");
        }
    }

//    public static void main(String[] args) {
//        ElmeOperateServiceImpl elmeOperateService = new ElmeOperateServiceImpl();
//        elmeOperateService.getEvaluateList(1L);
//    }
        public static MeiTuanOperateServiceImpl.Range getRange() {
            // 获取今天的日期和时间
            LocalDateTime today = LocalDateTime.now();

            // 获取前10天的日期和时间
            LocalDateTime tenDaysAgo = today.minusDays(10);

            // 定义日期和时间的格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'");

            // 格式化并打印今天的日期和时间
            String todayFormatted = today.format(formatter);
            System.out.println("Today: " + todayFormatted);

            // 格式化并打印前10天的日期和时间
            String tenDaysAgoFormatted = tenDaysAgo.format(formatter);
            System.out.println("10 days ago: " + tenDaysAgoFormatted);

            // 打印时间戳
            MeiTuanOperateServiceImpl.Range range = new MeiTuanOperateServiceImpl.Range();
            range.setStartTime(tenDaysAgoFormatted+"00:00:00");
            range.setEndTime(todayFormatted+"00:00:00");
            return range;
        }

}
